package comgame.scenes;

import com.almasb.fxgl.app.scene.FXGLScene;
import com.almasb.fxgl.dsl.FXGL;
import javafx.animation.TranslateTransition;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;

import java.util.Objects;
import javafx.scene.control.Label;
import javafx.scene.input.KeyCode;
import com.almasb.fxgl.input.UserAction;
import javafx.scene.layout.BorderPane;
import javafx.animation.Timeline;
import com.almasb.fxgl.audio.Sound;
import javafx.animation.KeyFrame;
import javafx.util.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javafx.scene.Node;
import javafx.scene.layout.HBox;
import javafx.scene.text.Font;
import javafx.scene.text.Text;

public class FishingScene extends FXGLScene {
    private static boolean actionRegistered = false;
    private enum State { WAITING, FISHING, TYPING, RESULT }
    private State state = State.WAITING;
    private BorderPane sceneRoot;
    private Label tipLabel;
    private Button backBtn;
    private ImageView floatIcon;
    private Timeline floatAnimation;
    private List<StackPane> bubbleNodes = new ArrayList<>();
    private int currentBubbleIndex = 0;
    private int errorCount = 0;
    private Timeline typingTimeout;
    private HBox bubbleBox;
    private static final int MAX_ERRORS = 3;
    private static final double BUBBLE_DURATION = 6.5; // 调整动画时间到6.5秒，平衡挑战性和可玩性
    private static FishingScene currentActiveScene = null;
    private javafx.event.EventHandler<javafx.scene.input.KeyEvent> typingHandler;
    private Timeline errorPauseTimeline;
    private static final double SCREEN_WIDTH = 800;
    private TranslateTransition bubbleTransition;
    // 新增：记录本次气泡数
    private int lastBubbleCount = 0;
    // 金币HUD相关
    private Label moneyLabel;
    private javafx.animation.Timeline moneyHudTimeline;
    // 新增：钓鱼阶段相关
    private static int fishingStage = 1; // 1: 第一阶段, 2: 第二阶段
    private ImageView backgroundView;
    private Label stageLabel;

    // 在类内添加静态变量
    private static comgame.scenes.MusicManager fishingMusicManager = new comgame.scenes.MusicManager();

    public FishingScene() {
        // 在构造函数中立即隐藏player实体，避免时序问题
        if (comgame.scenes.GameScene.playerEntity != null) {
            comgame.scenes.GameScene.playerEntity.getViewComponent().setVisible(false);
        }
        currentActiveScene = this;
        initUI();
    }

    private void initUI() {
        sceneRoot = new BorderPane();
        sceneRoot.setPrefSize(800, 600);

        // 加载钓鱼背景（根据阶段选择不同背景）
        String backgroundPath = fishingStage == 1 ?
                "/assets/textures/FishingSceneBackground.png" :
                "/assets/textures/Fishing_Background2.png";
        Image bgImg = new Image(Objects.requireNonNull(getClass().getResourceAsStream(backgroundPath)));
        backgroundView = new ImageView(bgImg);
        backgroundView.setFitWidth(1000);
        backgroundView.setFitHeight(750);
        sceneRoot.getChildren().add(backgroundView);

        // 创建顶部容器来包含返回按钮和阶段标签
        HBox topContainer = new HBox(20);
        topContainer.setAlignment(Pos.TOP_LEFT);
        topContainer.setPadding(new Insets(20, 0, 0, 20));

        // 返回按钮
        backBtn = new Button("返回");
        backBtn.setStyle("-fx-background-color: #E74C3C; -fx-text-fill: white; -fx-font-size: 16px; -fx-padding: 10 20;");
        backBtn.setOnMouseClicked(e -> {
            FXGL.getGameScene().clearUINodes();
            MapScene mapScene = new MapScene();
            FXGL.getGameScene().addUINode(mapScene.getSceneRoot());
            // 确保player实体可见
            if (comgame.scenes.GameScene.playerEntity != null) {
                comgame.scenes.GameScene.playerEntity.getViewComponent().setVisible(true);
            }
            // 在返回主界面（如MapScene、GameScene等）时，stopAll再播放HomeMusic
            comgame.scenes.MusicManager.stopAll();
            if (!comgame.scenes.MusicManager.isHomeMusicPlaying) {
                if (comgame.scenes.MusicManager.homeMusic == null)
                    comgame.scenes.MusicManager.homeMusic = FXGL.getAssetLoader().loadMusic("HomeMusic.mp4");
                FXGL.getAudioPlayer().loopMusic(comgame.scenes.MusicManager.homeMusic);
                comgame.scenes.MusicManager.isHomeMusicPlaying = true;
            }
        });

        // 阶段显示标签
        stageLabel = new Label("钓鱼阶段: " + fishingStage);
        stageLabel.setStyle("-fx-font-size: 18px; -fx-text-fill: white; -fx-background-color: rgba(0,0,0,0.6); -fx-padding: 5 15; -fx-background-radius: 5;");

        // 将按钮和标签添加到顶部容器
        topContainer.getChildren().addAll(backBtn, stageLabel);
        sceneRoot.setTop(topContainer);

        // 底部提示
        tipLabel = new Label("按 K 开始钓鱼 (需要25金币),钓鱼需要耐心,越耐心可能钓到更好的鱼！");
        tipLabel.setStyle("-fx-font-size: 22px; -fx-font-weight: bold; -fx-text-fill: linear-gradient(to bottom,#FFD700,#FFA500 60%,#FF8C00); -fx-stroke: #333; -fx-stroke-width: 2; -fx-effect: dropshadow(gaussian, #000, 8, 0.5, 2, 2); -fx-padding: 12 28; -fx-background-radius: 12; -fx-background-color: rgba(0,0,0,0.18);");
        BorderPane.setAlignment(tipLabel, Pos.BOTTOM_CENTER);
        BorderPane.setMargin(tipLabel, new Insets(0, 0, 40, 0));
        sceneRoot.setBottom(tipLabel);

        // 将场景根节点添加到内容根
        getContentRoot().getChildren().add(sceneRoot);

        // 金币HUD
        moneyLabel = new Label();
        moneyLabel.setText((comgame.scenes.GameScene.player != null ? comgame.scenes.GameScene.player.getMoney() : 0) + "￥");
        moneyLabel.setStyle("-fx-font-size: 22px; -fx-font-weight: bold; -fx-text-fill: #FFD700; -fx-background-color: rgba(0,0,0,0.18); -fx-padding: 8 18; -fx-background-radius: 12;");
        // 放在右上角
        BorderPane.setAlignment(moneyLabel, Pos.TOP_RIGHT);
        BorderPane.setMargin(moneyLabel, new Insets(12, 18, 0, 0));
        sceneRoot.setRight(moneyLabel);
        // 实时刷新
        moneyHudTimeline = new javafx.animation.Timeline(
            new javafx.animation.KeyFrame(javafx.util.Duration.seconds(0.1), e -> updateMoneyHUD())
        );
        moneyHudTimeline.setCycleCount(javafx.animation.Animation.INDEFINITE);
        moneyHudTimeline.play();

        // 钓鱼界面进入时切换为FishingMusic
        comgame.scenes.MusicManager.stopAll();
        if (!comgame.scenes.MusicManager.isFishingMusicPlaying) {
            if (comgame.scenes.MusicManager.fishingMusic == null)
                comgame.scenes.MusicManager.fishingMusic = FXGL.getAssetLoader().loadMusic("FishingMusic.mp4");
            FXGL.getAudioPlayer().loopMusic(comgame.scenes.MusicManager.fishingMusic);
            comgame.scenes.MusicManager.isFishingMusicPlaying = true;
        }

        // 只注册一次K键监听，操作currentActiveScene
        if (!actionRegistered) {
            FXGL.getInput().addAction(new UserAction("StartFishing") {
                @Override
                protected void onActionBegin() {
                    if (currentActiveScene != null && currentActiveScene.state == State.WAITING) {
                        currentActiveScene.startFishing();
                    }
                }
            }, KeyCode.K);
            actionRegistered = true;
        }
    }


    private void startFishing() {
        // 检查玩家金币是否足够
        if (comgame.scenes.GameScene.player != null) {
            if (comgame.scenes.GameScene.player.getMoney() < 25) {
                tipLabel.setText("金币不足！钓鱼需要25金币");
                tipLabel.setVisible(true);
                return;
            }
            // 扣除钓鱼费用
            comgame.scenes.GameScene.player.addMoney(-25);
            updateMoneyHUD();
        }
        
        state = State.FISHING;
        tipLabel.setVisible(false);
        if (backBtn != null) backBtn.setVisible(false);
        // 播放抛竿音效
        Sound fishingSound = FXGL.getAssetLoader().loadSound("fishing.wav");
        FXGL.getAudioPlayer().playSound(fishingSound);
        showFloatIcon();
        startFloatAnimation();
        
        // 增加钓鱼的随机性和真实感
        double randomFactor = Math.random();
        int waitTime;
        if (randomFactor < 0.4) {
            // 40%概率快速上钩（2-4秒）
            waitTime = 2 + (int)(Math.random() * 3);
        } else if (randomFactor < 0.8) {
            // 40%概率中等时间（4-6秒）
            waitTime = 4 + (int)(Math.random() * 3);
        } else {
            // 20%概率慢速上钩（6-9秒）
            waitTime = 5 + (int)(Math.random() * 4);
        }
        
        FXGL.runOnce(() -> {
            stopFloatAnimation();
            hideFloatIcon();
            showTypingGame();
        }, javafx.util.Duration.seconds(waitTime));
    }

    private void showFloatIcon() {
        if (floatIcon == null) {
            floatIcon = new ImageView(new Image(Objects.requireNonNull(getClass().getResourceAsStream("/assets/textures/Fishing.png"))));
            floatIcon.setFitWidth(64);
            floatIcon.setFitHeight(64);
        }
        floatIcon.setTranslateX(0);
        floatIcon.setTranslateY(180); // 屏幕下方水面
        sceneRoot.setCenter(floatIcon);
    }

    private void hideFloatIcon() {
        sceneRoot.setCenter(null);
    }

    private void startFloatAnimation() {
        floatAnimation = new Timeline(
                new KeyFrame(javafx.util.Duration.ZERO, e -> floatIcon.setTranslateX(-6)),
                new KeyFrame(javafx.util.Duration.seconds(0.6), e -> floatIcon.setTranslateX(6)),
                new KeyFrame(javafx.util.Duration.seconds(1.2), e -> floatIcon.setTranslateX(-6))
        );
        floatAnimation.setCycleCount(Timeline.INDEFINITE);
        floatAnimation.play();
    }

    private void stopFloatAnimation() {
        if (floatAnimation != null) {
            floatAnimation.stop();
        }
    }

    // 钓到鱼时播放音效
    private void playGotFishSound() {
        Sound gotFishSound = FXGL.getAssetLoader().loadSound("GotFish.wav");
        FXGL.getAudioPlayer().playSound(gotFishSound);
    }

    // 在浮漂等待后调用
    private void showTypingGame() {
        state = State.TYPING;
        currentBubbleIndex = 0;
        errorCount = 0;
        bubbleNodes.clear();
        if (bubbleBox != null) sceneRoot.setCenter(null);

        // 创建气泡容器
        bubbleBox = new HBox(20);
        bubbleBox.setAlignment(Pos.CENTER_LEFT);
        bubbleBox.setTranslateY(100);

        // 随机生成气泡数（第二阶段难度增加）
        Random random = new Random();
        double r = Math.random();
        int bubbleCount;
        
        if (fishingStage == 1) {
            // 第一阶段：4~8个字母，平衡难度
            if (r < 0.5) {
                bubbleCount = 4 + random.nextInt(2); // 4或5
            } else if (r < 0.9) {
                bubbleCount = 6 + random.nextInt(2); // 6或7
            } else {
                bubbleCount = 8;
            }
        } else {
            // 第二阶段：5~10个字母（难度+1）
            if (r < 0.5) {
                bubbleCount = 5 + random.nextInt(2); // 5或6
            } else if (r < 0.9) {
                bubbleCount = 7 + random.nextInt(2); // 7或8
            } else {
                bubbleCount = 9 + random.nextInt(2); // 9或10
            }
        }
        lastBubbleCount = bubbleCount; // 记录本次气泡数

        // 创建气泡
        for (int i = 0; i < bubbleCount; i++) {
            char letter = (char)('A' + random.nextInt(26));
            StackPane bubble = createBubble(letter);
            bubbleNodes.add(bubble);
            bubbleBox.getChildren().add(bubble);
        }

        // 添加到场景
        sceneRoot.setCenter(bubbleBox);

        // 创建移动动画 (从右向左)
        createBubbleMoveAnimation();

        // 设置超时检测
        typingTimeout = new Timeline(new KeyFrame(Duration.seconds(BUBBLE_DURATION), e -> onTypingTimeout()));
        typingTimeout.play();

        // 注册键盘监听
        addTypingHandler();
    }

    private void createBubbleMoveAnimation() {
        // 创建移动动画
        bubbleTransition = new TranslateTransition(Duration.seconds(BUBBLE_DURATION), bubbleBox);

        // 设置起始位置 (屏幕右侧外)
        bubbleBox.setTranslateX(SCREEN_WIDTH + 100);

        // 设置结束位置 (屏幕左侧外)
        bubbleTransition.setToX(-(bubbleBox.getChildren().size() * 84 + 100)); // 84 = 64(气泡) + 20(间距)

        // 设置动画完成时的回调
        bubbleTransition.setOnFinished(e -> {
            // 动画结束后检查是否还在游戏中
            if (state == State.TYPING) {
                onTypingTimeout();
            }
        });

        // 开始动画
        bubbleTransition.play();
        System.out.println("气泡动画已启动");
    }

    private StackPane createBubble(char letter) {
        // 使用Bubble.png作为底图
        ImageView bubbleImg = new ImageView(new Image(Objects.requireNonNull(getClass().getResourceAsStream("/assets/textures/Bubble.png"))));
        bubbleImg.setPreserveRatio(true);
        bubbleImg.setFitWidth(64);
        bubbleImg.setFitHeight(64);
        Text text = new Text(String.valueOf(letter));
        text.setFont(Font.font("Consolas", 32));
        text.setFill(Color.DARKBLUE);
        return new StackPane(bubbleImg, text);
    }

    private void addTypingHandler() {
        removeTypingHandler();
        typingHandler = event -> {
            if (state != State.TYPING) return;
            if (errorPauseTimeline != null && errorPauseTimeline.getStatus() == Timeline.Status.RUNNING) return;

            String input = event.getCharacter().toUpperCase();
            if (input.isEmpty()) return;

            char typed = input.charAt(0);

            // 检查是否还有气泡
            if (currentBubbleIndex >= bubbleNodes.size()) {
                return;
            }

            // 获取当前气泡
            StackPane currentBubble = bubbleNodes.get(currentBubbleIndex);
            Text text = findTextNode(currentBubble);

            if (text == null) {
                return;
            }

            char expected = text.getText().toUpperCase().charAt(0);

            if (typed == expected) {
                // 正确：播放音效并移除气泡
                playPopSound();
                bubbleBox.getChildren().remove(currentBubble);
                currentBubbleIndex++;

                // 检查是否完成所有气泡
                if (currentBubbleIndex == bubbleNodes.size()) {
                    typingTimeout.stop();
                    bubbleTransition.stop(); // 停止动画
                    onTypingSuccess();
                }
            } else {
                // 错误：播放音效并增加错误计数
                playSplashSound();
                errorCount++;

                // 错误暂停效果
                errorPauseTimeline = new Timeline(new KeyFrame(Duration.seconds(0.3)));
                errorPauseTimeline.setCycleCount(1);
                errorPauseTimeline.play();

                // 检查错误次数
                if (errorCount >= MAX_ERRORS) {
                    typingTimeout.stop();
                    bubbleTransition.stop(); // 停止动画
                    onTypingFail();
                }
            }
        };

        // 注册键盘监听
        FXGL.getPrimaryStage().getScene().addEventHandler(javafx.scene.input.KeyEvent.KEY_TYPED, typingHandler);
        System.out.println("键盘监听已注册");
    }

    private Text findTextNode(Node parent) {
        if (parent instanceof Text) {
            return (Text) parent;
        }

        if (parent instanceof javafx.scene.Parent) {
            for (Node child : ((javafx.scene.Parent) parent).getChildrenUnmodifiable()) {
                Text result = findTextNode(child);
                if (result != null) {
                    return result;
                }
            }
        }

        return null;
    }

    private void removeTypingHandler() {
        if (typingHandler != null) {
            FXGL.getPrimaryStage().getScene().removeEventHandler(javafx.scene.input.KeyEvent.KEY_TYPED, typingHandler);
            typingHandler = null;
        }
    }

    private void playPopSound() {
        Sound pop = FXGL.getAssetLoader().loadSound("pop.wav");
        FXGL.getAudioPlayer().playSound(pop);
    }

    private void playSplashSound() {
        Sound splash = FXGL.getAssetLoader().loadSound("splash.wav");
        FXGL.getAudioPlayer().playSound(splash);
    }

    // 实时刷新金币HUD
    private void updateMoneyHUD() {
        if (moneyLabel != null) {
            moneyLabel.setText((comgame.scenes.GameScene.player != null ? comgame.scenes.GameScene.player.getMoney() : 0) + "￥");
        }
    }

    // 在钓鱼成功、失败、超时等结算后都刷新金币HUD
    private void onTypingSuccess() {
        state = State.RESULT;
        playGotFishSound();
        updateMoneyHUD();

        // 根据钓鱼阶段处理不同的掉落逻辑
        if (fishingStage == 1) {
            handleStage1Fishing();
        } else {
            handleStage2Fishing();
        }
    }

    // 第一阶段钓鱼逻辑
    private void handleStage1Fishing() {
        // 4-5气泡特殊掉落逻辑
        if (lastBubbleCount == 4 || lastBubbleCount == 5) {
            String[] items = {"钓上来的头骨", "稀有破烂", "石头", "臭靴子", "木头"};
            String[] imageNames = {
                    "/assets/textures/Fishing_DeadPeople.png",
                    "/assets/textures/Fishing_RareStuff.png",
                    "/assets/textures/Fishing_Rock.png",
                    "/assets/textures/Fishing_Stinky_Boost.png",
                    "/assets/textures/Fishing_Wood.png"
            };
            double[] probs = {0.2375, 0.05, 0.2375, 0.2375, 0.2375};
            double r = Math.random();
            double acc = 0;
            int idx = 0;
            for (int i = 0; i < probs.length; i++) {
                acc += probs[i];
                if (r < acc) {
                    idx = i;
                    break;
                }
            }
            comgame.scenes.ItemManager.getInstance().addItem(items[idx], 1);
            tipLabel.setText("这钓的都啥啊");
            tipLabel.setVisible(true);
            
            // 安全加载图片
            javafx.scene.image.ImageView itemImg = new javafx.scene.image.ImageView();
            try {
                java.io.InputStream is = getClass().getResourceAsStream(imageNames[idx]);
                if (is != null) {
                    javafx.scene.image.Image img = new javafx.scene.image.Image(is);
                    itemImg.setImage(img);
                } else {
                    System.err.println("警告: 无法加载图片 " + imageNames[idx]);
                }
            } catch (Exception e) {
                System.err.println("加载图片时出错: " + e.getMessage());
            }
            
            // 钓鱼结算物品显示优化
            // 物品图片放大
            itemImg.setFitWidth(96);
            itemImg.setFitHeight(96);
            // 文字放大
            javafx.scene.control.Label nameLabel = new javafx.scene.control.Label(items[idx]);
            nameLabel.setStyle("-fx-font-size: 36px; -fx-text-fill: #fff; -fx-font-weight: bold; -fx-padding: 8 16;");
            javafx.scene.layout.VBox vbox = new javafx.scene.layout.VBox(10, itemImg, nameLabel);
            // VBox居中且无margin
            vbox.setAlignment(javafx.geometry.Pos.CENTER);
            vbox.setPadding(javafx.geometry.Insets.EMPTY);
            vbox.setStyle("");
            vbox.setTranslateX(40); // 向右平移40像素
            sceneRoot.setCenter(vbox);
            removeTypingHandler();
            FXGL.runOnce(this::resetToWaiting, javafx.util.Duration.seconds(2));
            return;
        }

        // 6-7气泡特殊掉落逻辑
        if (lastBubbleCount == 6 || lastBubbleCount == 7) {
            String[] items = {"稀有破烂", "橙鱼", "粉鱼"};
            String[] imageNames = {
                    "/assets/textures/Fishing_RareStuff.png",     // 使用现有图片替代
                    "/assets/textures/Fishing_orange.png",       // 使用现有图片替代
                    "/assets/textures/Fishing_pink.png"      // 使用现有图片替代
            };
            double[] probs = {0.2, 0.4, 0.4};
            double r = Math.random();
            double acc = 0;
            int idx = 0;
            for (int i = 0; i < probs.length; i++) {
                acc += probs[i];
                if (r < acc) {
                    idx = i;
                    break;
                }
            }
            if (idx == 0) {
                comgame.scenes.ItemManager.getInstance().addItem(items[idx], 1);
            } else if (idx == 1) {
                comgame.scenes.FishpoolScene.orangeFishCount++;
            } else if (idx == 2) {
                comgame.scenes.FishpoolScene.pinkFishCount++;
            }
            tipLabel.setText("终于钓上东西了！");
            tipLabel.setVisible(true);
            
            // 安全加载图片
            javafx.scene.image.ImageView itemImg = new javafx.scene.image.ImageView();
            try {
                java.io.InputStream is = getClass().getResourceAsStream(imageNames[idx]);
                if (is != null) {
                    javafx.scene.image.Image img = new javafx.scene.image.Image(is);
                    itemImg.setImage(img);
                } else {
                    System.err.println("警告: 无法加载图片 " + imageNames[idx]);
                }
            } catch (Exception e) {
                System.err.println("加载图片时出错: " + e.getMessage());
            }
            
            // 钓鱼结算物品显示优化
            // 物品图片放大
            itemImg.setFitWidth(96);
            itemImg.setFitHeight(96);
            // 文字放大
            javafx.scene.control.Label nameLabel = new javafx.scene.control.Label(items[idx]);
            nameLabel.setStyle("-fx-font-size: 36px; -fx-text-fill: #fff; -fx-font-weight: bold; -fx-padding: 8 16;");
            javafx.scene.layout.VBox vbox = new javafx.scene.layout.VBox(10, itemImg, nameLabel);
            // VBox居中且无margin
            vbox.setAlignment(javafx.geometry.Pos.CENTER);
            vbox.setPadding(javafx.geometry.Insets.EMPTY);
            vbox.setStyle("");
            vbox.setTranslateX(40); // 向右平移40像素
            sceneRoot.setCenter(vbox);
            removeTypingHandler();
            FXGL.runOnce(this::resetToWaiting, javafx.util.Duration.seconds(2));
            return;
        }

        // 8个气泡：钓鱼王，升级到第二阶段
        if (lastBubbleCount == 8) {
            comgame.scenes.FishpoolScene.redKingFishCount++;
            tipLabel.setText("我去！钓上鱼王了！钓鱼界面升级！");
            tipLabel.setVisible(true);
            
            // 安全加载图片
            javafx.scene.image.ImageView itemImg = new javafx.scene.image.ImageView();
            try {
                java.io.InputStream is = getClass().getResourceAsStream("/assets/textures/fish_red_King.png");
                if (is != null) {
                    javafx.scene.image.Image img = new javafx.scene.image.Image(is);
                    itemImg.setImage(img);
                } else {
                    System.err.println("警告: 无法加载鱼王图片");
                }
            } catch (Exception e) {
                System.err.println("加载鱼王图片时出错: " + e.getMessage());
            }
            
            // 钓鱼结算物品显示优化
            // 物品图片放大
            itemImg.setFitWidth(96);
            itemImg.setFitHeight(96);
            // 文字放大
            javafx.scene.control.Label nameLabel = new javafx.scene.control.Label("鱼王");
            nameLabel.setStyle("-fx-font-size: 36px; -fx-text-fill: #fff; -fx-font-weight: bold; -fx-padding: 8 16;");
            javafx.scene.layout.VBox vbox = new javafx.scene.layout.VBox(10, itemImg, nameLabel);
            // VBox居中且无margin
            vbox.setAlignment(javafx.geometry.Pos.CENTER);
            vbox.setPadding(javafx.geometry.Insets.EMPTY);
            vbox.setStyle("");
            vbox.setTranslateX(40); // 向右平移40像素
            sceneRoot.setCenter(vbox);
            removeTypingHandler();
            
            // 升级到第二阶段
            FXGL.runOnce(() -> {
                upgradeToStage2();
                resetToWaiting();
            }, javafx.util.Duration.seconds(2));
            return;
        }

        // 其他气泡数：原有"钓到鱼啦！"逻辑
        Label successLabel = new Label("钓到鱼啦！");
        successLabel.setStyle("-fx-font-size: 48px; -fx-text-fill: gold; -fx-font-weight: bold;");
        sceneRoot.setCenter(successLabel);

        tipLabel.setText("恭喜你钓到了一条鱼！");
        tipLabel.setVisible(true);

        removeTypingHandler();
        FXGL.runOnce(this::resetToWaiting, Duration.seconds(2));
    }

    // 第二阶段钓鱼逻辑
    private void handleStage2Fishing() {
        // 第二阶段：贝壳、珊瑚、死鱼、北极甜虾、良子鱼、洞穴鲨鱼
        if (lastBubbleCount >= 5 && lastBubbleCount <= 7) {
            // 贝壳、珊瑚、死鱼、北极甜虾
            String[] items = {"贝壳", "珊瑚", "死鱼", "北极甜虾"};
            String[] imageNames = {
                    "/assets/textures/Fishing_Clam.png",
                    "/assets/textures/Fishing_Coral.png", 
                    "/assets/textures/Fishing_DeadFish.png",
                    "/assets/textures/fish_ArcticShrimp.png"
            };
            double[] probs = {0.25, 0.25, 0.25, 0.25};
            double r = Math.random();
            double acc = 0;
            int idx = 0;
            for (int i = 0; i < probs.length; i++) {
                acc += probs[i];
                if (r < acc) {
                    idx = i;
                    break;
                }
            }
            
            // 只有北极甜虾是3只，其他是1只
            int count = (idx == 3) ? 3 : 1; // 北极甜虾是第4个（索引3）
            // 修改：北极甜虾不进仓库，只增加计数
            if (idx == 3) {
                comgame.scenes.FishpoolScene.arcticShrimpCount += 3;
            } else {
                comgame.scenes.ItemManager.getInstance().addItem(items[idx], count);
            }
            
            String countText = count == 3 ? "3个" : "1个";
            tipLabel.setText("钓到了" + countText + items[idx] + "！");
            tipLabel.setVisible(true);
            
            // 安全加载图片
            javafx.scene.image.ImageView itemImg = new javafx.scene.image.ImageView();
            try {
                java.io.InputStream is = getClass().getResourceAsStream(imageNames[idx]);
                if (is != null) {
                    javafx.scene.image.Image img = new javafx.scene.image.Image(is);
                    itemImg.setImage(img);
                } else {
                    System.err.println("警告: 无法加载图片 " + imageNames[idx]);
                }
            } catch (Exception e) {
                System.err.println("加载图片时出错: " + e.getMessage());
            }
            
            // 钓鱼结算物品显示优化
            // 物品图片放大
            itemImg.setFitWidth(96);
            itemImg.setFitHeight(96);
            // 文字放大
            javafx.scene.control.Label nameLabel = new javafx.scene.control.Label(items[idx] + " x" + count);
            nameLabel.setStyle("-fx-font-size: 36px; -fx-text-fill: #fff; -fx-font-weight: bold; -fx-padding: 8 16;");
            javafx.scene.layout.VBox vbox = new javafx.scene.layout.VBox(10, itemImg, nameLabel);
            // VBox居中且无margin
            vbox.setAlignment(javafx.geometry.Pos.CENTER);
            vbox.setPadding(javafx.geometry.Insets.EMPTY);
            vbox.setStyle("");
            vbox.setTranslateX(80); // 向右平移80像素（原40）
            vbox.setTranslateY(40); // 向下平移40像素（原0）
            sceneRoot.setCenter(vbox);
            removeTypingHandler();
            FXGL.runOnce(this::resetToWaiting, javafx.util.Duration.seconds(2));
            return;
        }
        
        if (lastBubbleCount == 8) {
            // 良子鱼（5秒15元）
            comgame.scenes.FishpoolScene.liangziFishCount++;
            tipLabel.setText("钓到了良子鱼！");
            tipLabel.setVisible(true);
            
            // 安全加载图片
            javafx.scene.image.ImageView itemImg = new javafx.scene.image.ImageView();
            try {
                java.io.InputStream is = getClass().getResourceAsStream("/assets/textures/fish_Jackfish.png");
                if (is != null) {
                    javafx.scene.image.Image img = new javafx.scene.image.Image(is);
                    itemImg.setImage(img);
                } else {
                    System.err.println("警告: 无法加载良子鱼图片");
                }
            } catch (Exception e) {
                System.err.println("加载良子鱼图片时出错: " + e.getMessage());
            }
            
            // 钓鱼结算物品显示优化
            // 物品图片缩小为72x72
            itemImg.setFitWidth(72);
            itemImg.setFitHeight(72);
            // 文字放大
            javafx.scene.control.Label nameLabel = new javafx.scene.control.Label("良子鱼");
            nameLabel.setStyle("-fx-font-size: 48px; -fx-text-fill: #fff; -fx-font-weight: bold; -fx-padding: 12 24;");
            javafx.scene.layout.VBox vbox = new javafx.scene.layout.VBox(10, itemImg, nameLabel);
            // VBox居中且无margin
            vbox.setAlignment(javafx.geometry.Pos.CENTER);
            vbox.setPadding(javafx.geometry.Insets.EMPTY);
            vbox.setStyle("");
            vbox.setTranslateX(180); // 向右平移180像素（原140）
            vbox.setTranslateY(80); // 向下平移80像素（原40）
            sceneRoot.setCenter(vbox);
            removeTypingHandler();
            FXGL.runOnce(this::resetToWaiting, javafx.util.Duration.seconds(2));
            return;
        }
        
        if (lastBubbleCount >= 9) {
            // 洞穴鲨鱼（5秒500元）
            comgame.scenes.FishpoolScene.caveSharkCount++;
            tipLabel.setText("钓到了洞穴鲨鱼！");
            tipLabel.setVisible(true);
            
            // 安全加载图片
            javafx.scene.image.ImageView itemImg = new javafx.scene.image.ImageView();
            try {
                java.io.InputStream is = getClass().getResourceAsStream("/assets/textures/fish_Caveshark.png");
                if (is != null) {
                    javafx.scene.image.Image img = new javafx.scene.image.Image(is);
                    itemImg.setImage(img);
                } else {
                    System.err.println("警告: 无法加载洞穴鲨鱼图片");
                }
            } catch (Exception e) {
                System.err.println("加载洞穴鲨鱼图片时出错: " + e.getMessage());
            }
            
            // 钓鱼结算物品显示优化
            // 物品图片缩小为72x72
            itemImg.setFitWidth(72);
            itemImg.setFitHeight(72);
            // 文字放大
            javafx.scene.control.Label nameLabel = new javafx.scene.control.Label("洞穴鲨鱼");
            nameLabel.setStyle("-fx-font-size: 48px; -fx-text-fill: #fff; -fx-font-weight: bold; -fx-padding: 12 24;");
            javafx.scene.layout.VBox vbox = new javafx.scene.layout.VBox(10, itemImg, nameLabel);
            // VBox居中且无margin
            vbox.setAlignment(javafx.geometry.Pos.CENTER);
            vbox.setPadding(javafx.geometry.Insets.EMPTY);
            vbox.setStyle("");
            vbox.setTranslateX(180); // 向右平移180像素（原140）
            vbox.setTranslateY(80); // 向下平移80像素（原40）
            sceneRoot.setCenter(vbox);
            removeTypingHandler();
            FXGL.runOnce(this::resetToWaiting, javafx.util.Duration.seconds(2));
            return;
        }

        // 其他气泡数：原有"钓到鱼啦！"逻辑
        Label successLabel = new Label("钓到鱼啦！");
        successLabel.setStyle("-fx-font-size: 48px; -fx-text-fill: gold; -fx-font-weight: bold;");
        sceneRoot.setCenter(successLabel);

        tipLabel.setText("恭喜你钓到了一条鱼！");
        tipLabel.setVisible(true);

        removeTypingHandler();
        FXGL.runOnce(this::resetToWaiting, Duration.seconds(2));
    }

    private void onTypingFail() {
        state = State.RESULT;
        updateMoneyHUD();

        // 显示失败消息
        Label failLabel = new Label("鱼溜走了！");
        failLabel.setStyle("-fx-font-size: 48px; -fx-text-fill: red; -fx-font-weight: bold;");
        sceneRoot.setCenter(failLabel);

        tipLabel.setText("再试一次吧！");
        tipLabel.setVisible(true);

        removeTypingHandler();
        FXGL.runOnce(this::resetToWaiting, Duration.seconds(2));
    }

    private void onTypingTimeout() {
        state = State.RESULT;
        updateMoneyHUD();

        // 显示超时消息
        Label timeoutLabel = new Label("超时，鱼跑了！");
        timeoutLabel.setStyle("-fx-font-size: 48px; -fx-text-fill: orange; -fx-font-weight: bold;");
        sceneRoot.setCenter(timeoutLabel);

        tipLabel.setText("动作要快一点哦！");
        tipLabel.setVisible(true);

        removeTypingHandler();
        FXGL.runOnce(this::resetToWaiting, Duration.seconds(2));
    }

    private void resetToWaiting() {
        state = State.WAITING;
        tipLabel.setText("按 K 开始钓鱼 (需要25金币)");
        tipLabel.setVisible(true);
        if (backBtn != null) backBtn.setVisible(true);
        sceneRoot.setCenter(null);
        bubbleNodes.clear();
        bubbleBox = null;
        currentBubbleIndex = 0;
        errorCount = 0;

        // 停止所有动画
        if (typingTimeout != null) typingTimeout.stop();
        if (bubbleTransition != null) bubbleTransition.stop();
        removeTypingHandler();
    }

    // 新增：升级到第二阶段
    private void upgradeToStage2() {
        fishingStage = 2;
        // 更新背景
        String backgroundPath = "/assets/textures/Fishing_Background2.png";
        Image bgImg = new Image(Objects.requireNonNull(getClass().getResourceAsStream(backgroundPath)));
        backgroundView.setImage(bgImg);
        // 更新阶段标签
        stageLabel.setText("钓鱼阶段: " + fishingStage);
    }

    public BorderPane getSceneRoot() {
        return sceneRoot;
    }
    public static void resetFishingStage() {
        fishingStage = 1;
    }
}